<template>
  <div class="order-list">
    <!-- 查询表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="申请人">
        <el-input v-model="searchForm.register" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="供应商公司名称">
        <el-input v-model="searchForm.supplierCompanyName" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="订单进度">
        <el-select v-model="searchForm.conveyTag" placeholder="全部" style="width: 150px">
          <el-option label="全部" value=""></el-option>
          <el-option label="已收货" value="已收货"></el-option>
          <el-option label="等待发货" value="等待发货"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购时间">
        <el-date-picker v-model="searchForm.registerTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="purchaseOrderNumber" label="订单编号" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showPurchaseOrderDetails(scope.row)">{{ scope.row.purchaseOrderNumber }} <i class="el-icon-view"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="supplierInfo" label="供应商公司(联系电话)" width="260" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showSupplierDetails(scope.row)">{{ scope.row.supplierInfo }} <i class="el-icon-view"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价格(元)" width="180" align="center"></el-table-column>
      <el-table-column prop="cya" label="采购人" width="180" align="center"></el-table-column>
      <el-table-column prop="registerTime" label="采购时间" width="250" align="center"></el-table-column>
      <el-table-column prop="conveyTag" label="订单进度" width="180" align="center">
        <template slot-scope="scope">
          <span :style="getStatusStyle(scope.row.conveyTag)">
            {{ scope.row.conveyTag }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <!-- 添加条件判断，仅当 conveyTag 为 P001-2 时显示查看收货按钮 -->
          <el-button v-if="scope.row.conveyTag === '待收货'" type="text" @click="receiveGoods(scope.row)">查看收货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
    >
    </el-pagination>
    <!-- 收货 Dialog -->
    <el-dialog :visible.sync="dialogVisible" width="70%">
      <div style="text-align: center">
        <h1>采购单(收货/入库)</h1>
      </div>
      <div class="dialog-content" style="width: 100%;">
        <div style="margin-bottom: 20px;">
          <el-row>
            <el-col :span="24" style="text-align: right">
              <el-button type="success"  class="el-icon-check" @click="confirmReceipt"> 确认收获/入库</el-button>
              <el-button type="danger" class="el-icon-refresh"> 返回</el-button>
            </el-col>
          </el-row>
        </div>
        <el-form label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单编号:">
                {{ selectedOrder.purchaseOrderNumber }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总计:">
                {{ selectedOrder.totalPrice }}元
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购人:">
                {{ selectedOrder.purchaser }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购时间:">
                {{ selectedOrder.registerTime }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="goodsTable" style="width: 100%;height: 500px">
          <el-table-column prop="image" label="图片" width="80" align="center">
            <template slot-scope="scope">
              <img :src="'/img'+scope.row.image" alt="商品图片" style="width: 50px; height: 50px;" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" width="200" align="center"></el-table-column>
          <el-table-column prop="price" label="单价(元)" width="150" align="center"></el-table-column>
          <el-table-column prop="unit" label="商品单位" width="150" align="center"></el-table-column>
          <el-table-column prop="count" label="数量(件)" width="150" align="center"></el-table-column>
          <el-table-column prop="confirmCount" label="确认数量(件)" width="180" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.confirmCount" placeholder="请输入数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="warehouse" label="仓库(最大存储量/当前已存储)" width="250" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.warehouse" placeholder="请选择仓库">
<!--                <el-option-->
<!--                    v-for="item in warehouses"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                ></el-option>-->
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <el-form ref="reviewForm" :model="reviewForm" label-width="120px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="入库人:" prop="reviewer">
                <el-input style="width: 200px" v-model="reviewForm.storer" placeholder="请输入库人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="申请入库时间:">
                <el-input style="width: 200px" v-model="reviewForm.storerTimeStr"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchForm: {
        register: "",
        supplierCompanyName: "",
        conveyTag: "",
        registerTime: []
      },
      orderStatus: '',
      tableData: [],
      goodsTable: [
        {
          productId:"",
          supplierId:"",
          image:"",
          name:"",
          price:"",
          unit:"",
          count:"",
          confirmCount:"",
          warehouse:"",
          currentStorageCapacity:""
        }
      ],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      selectedOrder: {}, // 当前选中的订单详情
      reviewForm: {
        storer: '',
        storerTimeStr: new Date().toISOString().split('T')[0],
        realAmount: ''
      }
    };
  },
  methods: {
    initTable() {
      Object.assign(this.searchForm, {"currentPage": this.currentPage, "pageSize": this.pageSize});
      this.$axios.post("http://localhost:8090/purchase-order/selectAllPurchaseOrder", this.searchForm).then(({ data }) => {

        this.tableData = data;
        this.total = data.total;
        this.tableData.map(item => (
          item.conveyTag = this.getConveyTagText(item.conveyTag),
          item.supplierInfo = item.supplier.companyName +"("+ item.supplier.phone +")"
        ));
      })
    },
    showPurchaseOrderDetails(row) {
      console.log(row);
    },
    //收货
    receiveGoods(row) {
      this.selectedOrder = row; // 保存选中的订单详情
      console.log('选中行：' + this.selectedOrder);
      this.$axios.get("http://localhost:8090/purchase-order-details/" + row.purchaseOrderNumber).then(({ data }) => {
        console.log('商品：'+data);
        this.goodsTable = data.map(item => (
          {
            productId: item.product.productId,
            supplierId: item.purchaseOrder.supplierId,
            image: item.product.imgLink,
            name: item.product.name,
            price: item.price,
            unit: item.product.unit,
            count: item.count,
            warehouse: '生鲜仓库(1000/'+item.product.stock+")",
            currentStorageCapacity: item.count
          }
        ));
      });
      this.dialogVisible = true; // 打开 Dialog
    },
    //提交收货/入库请求
    confirmReceipt() {
      console.log('确认收货/入库');
      // 校验入库人是否输入
      if (!this.reviewForm.storer) {
        this.$message({
          type: 'warning',
          message: '请输入入库人'
        });
        return;
      }

      // 校验每个商品的确认数量是否输入
      const invalidItems = this.goodsTable.filter(item => !item.confirmCount || item.confirmCount <= 0);
      if (invalidItems.length > 0) {
        this.$message({
          type: 'warning',
          message: '请填写所有商品的确认数量'
        });
        return;
      }
      let purchaseOrder = this.selectedOrder;
      console.log('purchaseOrder:', purchaseOrder);
      //采购订单id
      let purchaseId = purchaseOrder.purchaseId;
      console.log('purchaseId:', purchaseId);
      //申请人
      let register = purchaseOrder.register;
      console.log('register:'+register);
      //申请时间
      let registerTime = purchaseOrder.registerTime;
      console.log('registerTime:'+registerTime);
      //总价格
      let totalPrice = purchaseOrder.totalPrice;
      console.log('totalPrice:'+totalPrice);
      //总数量
      let totalAmount = purchaseOrder.totalAmount;
      console.log('totalAmount:'+totalAmount);
      //入库人
      let storer = this.reviewForm.storer;
      console.log('storer:'+storer);
      let infoItem = {
        purchaseId: purchaseId,
        register: register,
        registerTime: registerTime,
        totalPrice: totalPrice,
        totalAmount: totalAmount,
        storer: storer
      };
      console.log('infoItem:', infoItem);
      let products = this.goodsTable.map(item => ({
        productId: item.productId,
        supplierId: item.supplierId,
        count: item.count, //应入库数量
        confirmCount: item.confirmCount, //实际入库数量
        price : item.price,
        subTotal: item.price * item.count
      }))
      products.map(item => { console.log(item)});
      console.log('products:'+products);
      let data = [infoItem,products];
      console.log('data:'+data);
      this.$confirm('确认收货/入库？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post("http://localhost:8090/gather/saveGather", data).then(({ data }) => {
          console.log(data);
          if(data){
            this.$message({
              type: 'success',
              message: '收货/入库成功!'
            });
            this.initTable();
            this.dialogVisible = false;
          }
        });
      })
    },
    showSupplierDetails(row) {
      console.log(row);
    },
    onSearch() {
      // 查询逻辑
    },
    onReset() {
      // 重置逻辑
    },
    handleSizeChange() {
      this.initTable()
    },
    handleCurrentChange() {
      this.initTable();
    },
    getConveyTagText(conveyTag) {
      switch (conveyTag) {
        case 'P001-1':
          return '待发货';
        case 'P001-2':
          return '待收货';
        case 'P001-3':
          return '已收货';
        default:
          return conveyTag;
      }
    },
    getStatusStyle(conveyTag) {
      switch (conveyTag) {
        case '已收获':
          return 'color: lightcoral;';
        case '待收货':
          return 'color: lightblue;';
        case '待发货':
          return 'color: lightgray';
        default:
          return '';
      }
    }
  },
  mounted() {
    this.initTable();
    // this.initWarehouses(); // 调用方法初始化仓库数据
  },
};
</script>

<style scoped>
.order-list {
  padding: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.el-table >>> .el-table__header tr th {
  background-color: lightgray;
  color: black;
}
</style>
